package org.finmanager.statistics;

import org.finmanager.core.Item;
import org.finmanager.data.CategoryList;
import org.finmanager.data.ItemList;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.PieDataset;

import java.util.Calendar;
import java.util.List;

/**
 * Created by Kelvin on 11/4/2014.
 */

//enhancing the pie chart
public class CategoryPieChartDataSet extends AbstractDataset implements PieDataset {
	//getting the categoryList, itemList to enhance the function in the pie chart
	private CategoryList categoryList;
	private ItemList itemList;

	private Calendar calendar = Calendar.getInstance();

	public CategoryPieChartDataSet(StatisticsModel statisticsModel) {
		this.itemList = statisticsModel.getItemList();
		this.categoryList = statisticsModel.getCategoryList();
	}

	@Override
	public Comparable getKey(int i) {
		return null;
	}

	@Override
	public int getIndex(Comparable comparable) {
		return categoryList.getList().indexOf(comparable);
	}

	@Override
	public List getKeys() {
		return categoryList.getList();
	}

	@Override
	public Number getValue(Comparable comparable) {
		Double amountSum = 0.0;
		for (Item item : itemList.getList()) {
			if (item.getCategory().equals(comparable) && checkItemTimeConstraint(item)) {
				amountSum += item.getAmount();
			}
		}
		return amountSum;
	}

	@Override
	public int getItemCount() {
		return itemList.getItemCount();
	}

	@Override
	public Number getValue(int i) {
		if (i >= categoryList.getCategoryCount()) {
			// There seems to be a bug in the library
			// When getValue is 0 for all category, this function with i >= categoryCount will be called
			// Adding return 0 will hide this problem
			return 0;
		}
		return getValue(categoryList.getCategory(i));
	}

	public boolean checkItemTimeConstraint(Item item) {
			return (item.getYear() == calendar.get(Calendar.YEAR) && item.getMonth() == calendar.get(Calendar.MONTH));
		}

	public void increaseMonth() {
		calendar.add(Calendar.MONTH, 1);
		fireDatasetChanged();
	}

	public void decreaseMonth() {
		calendar.add(Calendar.MONTH, -1);
		fireDatasetChanged();
	}

	public void setCalendar(Calendar calendar) {
		this.calendar = calendar;
		fireDatasetChanged();
	}

	public Calendar getCalendar() {
		return calendar;
	}

	@Override
	public void fireDatasetChanged() {
		super.fireDatasetChanged();
	}
}
